import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useUserStore } from '../store/userStore'

// 权限控制 Hook
export const useAuth = () => {
  const { isLoggedIn, userInfo } = useUserStore()
  const navigate = useNavigate()

  // 检查是否已登录
  const checkAuth = () => {
    if (!isLoggedIn) {
      navigate('/login')
      return false
    }
    return true
  }

  // 检查用户权限
  const checkPermission = (permission) => {
    if (!isLoggedIn) {
      return false
    }
    
    // 这里可以根据实际需求实现权限检查逻辑
    // 例如检查用户角色、权限列表等
    const userRole = userInfo.role || 'user'
    
    // 简单的权限检查示例
    const permissionMap = {
      admin: ['read', 'write', 'delete', 'admin'],
      manager: ['read', 'write'],
      user: ['read']
    }
    
    return permissionMap[userRole]?.includes(permission) || false
  }

  // 检查用户角色
  const checkRole = (role) => {
    if (!isLoggedIn) {
      return false
    }
    
    const userRole = userInfo.role || 'user'
    return userRole === role
  }

  // 自动检查权限（在组件挂载时）
  useEffect(() => {
    checkAuth()
  }, [isLoggedIn])

  return {
    isLoggedIn,
    userInfo,
    checkAuth,
    checkPermission,
    checkRole
  }
}

// 权限路由组件 Hook
export const usePermissionRoute = (requiredPermission) => {
  const { checkPermission } = useAuth()
  
  useEffect(() => {
    if (requiredPermission && !checkPermission(requiredPermission)) {
      // 如果没有权限，可以跳转到无权限页面或显示提示
      console.warn('您没有访问该页面的权限')
    }
  }, [requiredPermission, checkPermission])
  
  return { hasPermission: checkPermission(requiredPermission) }
}
